<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box1{width:100px;height:100px;background:red;position: absolute;left:0;top:0;}
        .box2{width:100px;height:100px;background:green;position: absolute;left:0;top:110px;}
    </style>
</head>
<body>
    <div class="box1"></div>
    <div class="box2"></div>
</body>
<script>
    function Drag(ele){
        this.ele = ele;
        this.m = this.move.bind(this);
        this.u = this.up.bind(this);
        this.addEvent()
    }
    Drag.prototype.addEvent = function(){
        this.ele.addEventListener("mousedown", this.down.bind(this));
    }
    Drag.prototype.down = function(eve){
        this.downE = eve || window.event;
        document.addEventListener("mousemove", this.m);
        document.addEventListener("mouseup", this.u);
    }
    Drag.prototype.move = function(eve){
        this.moveE = eve || window.event;
        this.ele.style.left = this.moveE.pageX - this.downE.offsetX + "px";
        this.ele.style.top = this.moveE.pageY - this.downE.offsetY + "px";
    }
    Drag.prototype.up = function(eve){
        document.removeEventListener("mousemove", this.m);
        document.removeEventListener("mouseup", this.u);
    }

    const box1 = document.querySelector(".box1")
    const box2 = document.querySelector(".box2")
    
    new Drag(box1);
    // new Drag(box2)

    // 基于原始的拖拽功能，先继承所有的拖拽功能
    class SmallDrag extends Drag{
        constructor(ele){
            super(ele)
        }
        // 改写移动方法，改成具有边界限定功能
        move(abc){
            this.moveE = abc || window.event;
            let l = this.moveE.pageX - this.downE.offsetX;
            let t = this.moveE.pageY - this.downE.offsetY;
            
            if(l<0) l=0;
            if(t<0) t=0;
            
            this.ele.style.left = l + "px";
            this.ele.style.top = t + "px";
        }
    }
    new SmallDrag(box2);

</script>
</html>